package com.yh.autobio.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yh.autobio.AppConfig;
import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.api.RetrofitSingleton;
import com.yh.autobio.base.BaseFragment;
import com.yh.autobio.common.CyptoUtils;
import com.yh.autobio.common.PLog;
import com.yh.autobio.common.StringUtils;
import com.yh.autobio.modules.adatper.SalaryReportAdapter;
import com.yh.autobio.modules.bean.CM;
import com.yh.autobio.modules.bean.HeaderBean;
import com.yh.autobio.modules.bean.Result;
import com.yh.autobio.modules.bean.TeamChild;
import com.yh.autobio.modules.bean.User;
import com.yh.autobio.modules.bean.WorkInfo;
import com.yh.autobio.modules.bean.WorkInfoGJDW;
import com.yh.autobio.modules.bean.WorkInfoSalary;
import com.yh.autobio.modules.bean.WorkInfoSalaryBean;
import com.yh.autobio.modules.bean.WorkSalaryBean;
import com.yh.autobio.modules.bean.t_my_gxhbdmxEntry;
import com.yh.autobio.modules.bean.t_my_pgdanEntry01;
import com.yh.autobio.modules.ui.LoginActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：john
 * <p/>
 * 工程：ZWSR
 * <p/>
 * 文件名：SalaryRepotFragment
 * <p/>
 * 创建时间：2016.10.25.14:10
 * *****************************
 */
public class SalaryRepotFragment extends BaseFragment {
    @InjectView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    private User user;
    String reportTime, id, workno;
    boolean isRun = false;//防止重复提交
    String retoken;
    HeaderBean headerBean;
    ArrayList<WorkInfo> mInfos = new ArrayList<>();
    String checkedUsers = "";
    String userName;
    private WorkSalaryBean workBean;
    Handler handler;

    ArrayList<t_my_pgdanEntry01> workusers = new ArrayList<>();
    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            Snackbar.make(mRecyclerView, e.getMessage(), Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();

            if (result != null) {
                Object objects = result.getData();
                if (objects != null) {
                    Gson gson = new Gson();
                    String json = gson.toJson(objects);
                    PLog.i("lj", json);
                    WorkInfoSalaryBean myWorkbean = gson.fromJson(json, new TypeToken<WorkInfoSalaryBean>() {
                    }.getType());
                    WorkInfoGJDW workInfoGJDW = myWorkbean.getWorkGJDW();
                    ArrayList<WorkInfoSalary> xxxxs = (ArrayList<WorkInfoSalary>) myWorkbean.getInfos();
                    workBean = new WorkSalaryBean();
                    workBean.setWorkInfos(xxxxs);
//                    workBean.setWorkusers(workusers);
                    showWaitDialog();
                    if (myWorkbean != null) {
                        headerBean.setCount_all(String.valueOf(workInfoGJDW.getFJSValue()));
                        headerBean.setfJSName(workInfoGJDW.getfJSName());
                        headerBean.setFJSValue_Done(workInfoGJDW.getFJSValue_Done());
//                        headerBean.setOneValue(workInfoGJDW.getFJSValue() / xxxxs.size());
                    }
                    workBean.setHeaderBean(headerBean);
                    workBean.setWorkusers(workusers);
                    adapter = new SalaryReportAdapter(SalaryRepotFragment.this, mActivity, workBean,startDate,endDate);
                    mRecyclerView.setAdapter(adapter);

                }else {
                    handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mActivity.finish();
                        }
                    },1000);
                    Snackbar.make(mRecyclerView,"暂无数据",Snackbar.LENGTH_SHORT).show();
                }
            }
        }
    };


    Observer<Result> observer1 = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
            isRun = false;
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            isRun = false;
            Snackbar.make(mRecyclerView, e.getMessage(), Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            isRun = false;
            if (result != null) {
                Object objects = result.getData();
                String message = result.getMessage();
                Gson gson = new Gson();
                if (objects != null) {
                    int code = result.getStatusCode();
                    if (code == 200) {
                        Snackbar.make(mRecyclerView, "提交工资汇报成功！", Snackbar.LENGTH_SHORT).show();
                        mActivity.finish();
                    } else {
                        Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                    }
                } else {
                    Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                }
            }
        }
    };

    private SalaryReportAdapter adapter;
    private Bundle bundle;
    private String startDate;
    private String endDate;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_workdetail, container, false);
        ButterKnife.inject(this, view);
        setHasOptionsMenu(true);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setHasFixedSize(true);
    }

    @Override
    public void initData() {
        super.initData();
        bundle = getArguments();
        String private_token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
        retoken = CyptoUtils.decode(AppConfig.key, private_token);
        headerBean = new HeaderBean();
        user = AppContext.getInstance().getCurrentUser();
        reportTime = StringUtils.getCurTimeStr();
        headerBean.setReportTime(reportTime);
        if (user != null) {
            headerBean.setHbcjgx(user.getDepartmentName() + "/" + user.getGXName());
            headerBean.setHbuser(user.getName());

        } else {
            Snackbar.make(mRecyclerView, "获取用户失败，请重新登录", Snackbar.LENGTH_SHORT).show();
            Intent main = new Intent(mActivity, LoginActivity.class);
            startActivity(main);
            mActivity.finish();
        }

        showWaitDialog("获取派工单详情...");
        startDate = bundle.getString("startDate");
        endDate = bundle.getString("endDate");
        RetrofitSingleton.getApiService(mActivity).
                WorksUnReported(retoken, user.getGXId(),user.getFDepartmentID(), startDate, endDate)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        int index_menu = 0;
        index_menu = R.menu.send_menu;
        inflater.inflate(index_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                if (adapter != null) {
                    if (adapter.isDYCountAll) {
                        ArrayList<t_my_pgdanEntry01> workusers = adapter.getWorkBean().getWorkusers();
                        Snackbar.make(mRecyclerView, "不能大于总面积", Snackbar.LENGTH_SHORT).show();
                        isRun = false;
                        return false;
                    } else {
                        if (!isRun) {
                            showWaitDialog();
                            if (adapter != null) {
                                WorkSalaryBean workBean1 = adapter.getWorkBean();
                                if (workBean1 != null) {
                                    boolean mf = false;
                                    ArrayList<WorkInfoSalary> mcinfos = workBean1.getWorkInfos();
                                    for (int m = 0; m < mcinfos.size(); m++) {
                                        if (mcinfos.get(m).getFWages()) {
                                            mf = true;
                                        }
                                    }
                                    if (mf) {
                                        if (mcinfos.size() == 0) {
                                            hideWaitDialog();
                                            isRun = false;
                                            Snackbar.make(mRecyclerView, "未选中任何内容", Snackbar.LENGTH_SHORT).show();
                                            return false;
                                        } else {
                                            workusers = workBean1.getWorkusers();
                                            if (workusers.size() < 1) {
                                                hideWaitDialog();
                                                isRun = false;
                                                Snackbar.make(mRecyclerView, "至少选择一个工人", Snackbar.LENGTH_SHORT).show();
                                                return false;
                                            }
                                            List<t_my_gxhbdmxEntry> t_my_gxhbdmxEntryList = new ArrayList<>();
                                            for (int j = 0; j < workusers.size(); j++) {

                                                t_my_gxhbdmxEntry gxhbdmxEntry = new t_my_gxhbdmxEntry();
                                                gxhbdmxEntry.setFIndex(j + 1);
                                                gxhbdmxEntry.setFgongxu(user.getGXId());
                                                gxhbdmxEntry.setFAmount(workusers.get(j).getFMoney());
                                                gxhbdmxEntry.setFHBUser(workusers.get(j).getFHBUserID());
                                                gxhbdmxEntry.setFPrice(workusers.get(j).getFPrice());
                                                gxhbdmxEntry.setFQty(workusers.get(j).getFAmount());
                                                t_my_gxhbdmxEntryList.add(gxhbdmxEntry);
                                            }
                                            String userjsonstr = new Gson().toJson(t_my_gxhbdmxEntryList);
                                            mcinfos.get(0).setFhbusers(userjsonstr);
                                            CM cm = new CM();
                                            cm.setToken(retoken);
                                            String jsonstr = new Gson().toJson(mcinfos);
                                            cm.setData(jsonstr);
                                            showWaitDialog();
                                            RetrofitSingleton.getApiService(mActivity).
                                                    WorkReportUpdate(cm)
                                                    .subscribeOn(Schedulers.io())
                                                    .observeOn(AndroidSchedulers.mainThread())
                                                    .subscribe(observer1);
                                            isRun = true;
                                        }
                                    } else {
                                        Snackbar.make(mRecyclerView, "未选中任何要汇报的单据或者单据已全部汇报！", Snackbar.LENGTH_SHORT).show();
                                        hideWaitDialog();
                                        isRun = false;
                                    }
                                }else {
                                    Snackbar.make(mRecyclerView, "未获得数据！", Snackbar.LENGTH_SHORT).show();
                                    hideWaitDialog();
                                    isRun = false;
                                }
                            } else {
                                mActivity.finish();
                            }
                        } else {
                            Snackbar.make(mRecyclerView, "本次正在提交中,请勿重复提交", Snackbar.LENGTH_SHORT).show();
                            showWaitDialog("提交中...");
                        }
                    }
                    break;
                }
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == mActivity.RESULT_OK) {
            switch (requestCode) {
                case 10:
                    if (data != null) {
                        Bundle bundle2 = data.getExtras();
                        if (bundle2 != null) {
                            ArrayList<TeamChild> checkedChildren = (ArrayList<TeamChild>) bundle2.getSerializable("checkedChildren");
                            checkedUsers = "";
                            workusers.clear();
                            if (checkedChildren != null) {
                                String name = "{" + userName + "}" + "、";
                                for (int i = 0; i < checkedChildren.size(); i++) {
                                    t_my_pgdanEntry01 worker = new t_my_pgdanEntry01();
                                    TeamChild child = checkedChildren.get(i);
                                    if (child != null) {
                                        if (!child.getName().equals(userName)) {
                                            worker.setFHBUserName(child.getName());
                                            worker.setFHBUserID(Integer.parseInt(child.getId()));
                                            workusers.add(worker);
                                            if (i == checkedChildren.size() - 1) {
                                                checkedUsers += child.getId();
                                                name += "{" + child.getName() + "}";
                                            } else {
                                                checkedUsers += child.getId() + ",";
                                                name += "{" + child.getName() + "}" + "、";
                                            }
                                        }
                                    }
                                }
                                workBean.setWorkusers(workusers);
                                adapter = new SalaryReportAdapter(SalaryRepotFragment.this, mActivity, workBean, startDate, endDate);
                                mRecyclerView.setAdapter(adapter);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
